package com.wuliu.servlet;

import com.wuliu.dao.UserDAO;
import com.wuliu.dao.impl.UserDAOImpl;
import com.wuliu.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/view/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        boolean admin =Boolean.valueOf(req.getParameter("admin"));
        System.out.println(account + password);
        UserDAO userDAO = new UserDAOImpl();
        User user = userDAO.findByAccount(account);
        if (user == null) {
            req.setAttribute("msg", "账号不存在");
            req.getRequestDispatcher("/WEB-INF/view/login.jsp").forward(req, resp);
            return;
        } else if (!user.getPassword().equals(password)) {
            req.setAttribute("msg", "密码错误");
            req.getRequestDispatcher("/WEB-INF/view/login.jsp").forward(req, resp);
            return;
        }
        req.getSession().setAttribute("user", user);
        req.getSession().setAttribute("admin",admin);
        resp.sendRedirect("/page1");
    }
}
